package com.sc.web.gwt.client.view.uicomponent;

import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Style;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.TextBox;

public class ValidatableTextBox extends TextBox {

    private TextBoxValidationHelper textBoxValidationHelper;
    private Timer changeTimer;

    public ValidatableTextBox() {
        textBoxValidationHelper = new TextBoxValidationHelper(this);
        changeTimer = new Timer() {
            @Override
            public void run() {
                ChangeEvent.fireNativeEvent(Document.get().createChangeEvent(), ValidatableTextBox.this);
            }
        };

        this.addKeyUpHandler(new KeyUpHandler() {
            public void onKeyUp(KeyUpEvent keyUpEvent) {
                changeTimer.schedule(1000);
            }
        });
    }

    public void showError(final String message) {
        textBoxValidationHelper.showErrorOnTextBox(message);
        this.getElement().getStyle().setBorderColor("red");
        this.getElement().getStyle().setBorderWidth(1 , Style.Unit.PX);
        this.getElement().getStyle().setBorderStyle(Style.BorderStyle.SOLID);
    }

    public void showOk() {
        textBoxValidationHelper.showOkOnTextBox();
    }

    public void clearStatus() {
        textBoxValidationHelper.clearStatusOnTextBox();
        this.getElement().getStyle().clearBorderColor();
        this.getElement().getStyle().clearBorderWidth();
        this.getElement().getStyle().clearBorderStyle();
    }
}
